package models

import (
	beego "github.com/beego/beego/v2/adapter"
	"github.com/beego/beego/v2/client/orm"
	"strconv"
	"strings"
	"time"
	"weiboxs.com/new_h_glasses/utils"
)

type WechatMessage struct {
	Id           int64
	DepartmentId int64
	Title        string
	Typeid       int
	Command      string
	Description  string
	Content      string
	Image        string
	Url          string
	RelationIds  string
	CreatedAt    int64
	UpdatedAt    int64
}

type WechatMessageParam struct {
	BaseQueryParam
	Filter       string
	DepartmentId int64
}

func (m *WechatMessage) TableName() string {
	return WechatMessageTableName()
}

func WechatMessageTableName() string {
	return TableName("wechat_message")
}

//查询一条数据
func (m *WechatMessage) One(id int64, department_id int64) *WechatMessage {
	orm.NewOrm().QueryTable(m.TableName()).Filter("DepartmentId", department_id).Filter("id", id).One(m)
	return m
}

//按关键字查询一条数据
func (m *WechatMessage) OneByKeyWord(keyword string) *WechatMessage {
	orm.NewOrm().QueryTable(m.TableName()).Filter("command", keyword).One(m)
	if m.Id <= 0 {
		if _, err := strconv.ParseInt(keyword, 0, 64); err == nil {
			orm.NewOrm().QueryTable(m.TableName()).Filter("command", "default").One(m)
		}
	}
	return m
}

//分页列表
func (m *WechatMessage) MessagePageList(params *WechatMessageParam) ([]*WechatMessage, int64) {
	query := orm.NewOrm().QueryTable(m.TableName())

	data := make([]*WechatMessage, 0)

	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	cond := orm.NewCondition()

	if params.Filter != "" {
		cond = cond.And("title__contains", params.Filter)
	}
	cond = cond.And("DepartmentId", params.DepartmentId)

	query = query.SetCond(cond)

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)

	return data, total
}

//保存消息
func (m *WechatMessage) Save(site string) error {
	m.Command = strings.ToLower(m.Command)
	if m.Id == 0 {
		m.CreatedAt = time.Now().Unix()
		m.UpdatedAt = m.CreatedAt
		if _, err := orm.NewOrm().Insert(m); err != nil {
			return err
		}
		if m.Typeid == 1 { //URL为空则自动生成URL地址
			en, _ := utils.Encrypt(strconv.FormatInt(m.Id, 10))

			m.Url = site + beego.URLFor("api.WechatController.Message", "encode", en)
			orm.NewOrm().Update(m, "url")
		}
	} else {
		m.UpdatedAt = time.Now().Unix()
		if m.Typeid == 1 { //URL为空则自动生成URL地址
			en, _ := utils.Encrypt(strconv.FormatInt(m.Id, 10))
			m.Url = site + beego.URLFor("api.WechatController.Message", "encode", en)
		}
		//fields, _ := utils.ReflectModelFields(m)
		if _, err := orm.NewOrm().Update(m); err != nil {
			return err
		}
	}
	return nil
}

//删除消息
func (m *WechatMessage) Del(id int64, cur BackendUser) error {
	orm := orm.NewOrm().QueryTable(m.TableName())
	if _, err := orm.Filter("id", id).Filter("DepartmentId", cur.DepartmentId).Delete(); err != nil {
		return err
	}
	return nil
}
